package com.yonyou.brigade.third_parties.ctripBC.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.yonyou.brigade.basic_init.enums.OpenTypeEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IBriSysConfigService;
import com.yonyou.brigade.basic_init.service.IMongoService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.common.model.ThirdProperty;
import com.yonyou.brigade.third_parties.common.service.IThirdPropertyService;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCConfig;
import com.yonyou.brigade.third_parties.ctripBC.model.CtripBCUser;
import com.yonyou.brigade.third_parties.ctripBC.model.PassengerDetailV2;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCPublicService;
import com.yonyou.brigade.third_parties.ctripBC.service.ICtripBCUserService;
import com.yonyou.brigade.third_parties.ctripBC.util.CtripBCUserConvertUtil;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.MD5Util;
import com.yonyou.ybz.ctrip.pojo.CtripGroupMember;
import com.yonyou.ybz.ctrip.service.ICtripGroupMemberService;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.thread.InvocationInfoProxy;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import corp.openapicalls.contract.Authentification;
import corp.openapicalls.contract.employee.*;
import corp.openapicalls.contract.ordercontroller.ticket.OrderSearchTicketResponse;
import corp.openapicalls.contract.setapproval.request.*;
import corp.openapicalls.contract.setapproval.response.SetApprovalResponse;
import corp.openapicalls.contract.ticket.TicketResponse;
import corp.openapicalls.service.employee.MultipleEmployeeSyncService;
import corp.openapicalls.service.setapproval.SetApprovalService;
import corp.openapicalls.service.ticket.CorpTicketService;
import net.sf.json.JSONSerializer;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

import static com.yonyou.brigade.util.resultutil.HttpSendUtils.sendPost;

@Service
public class CtripBCPublicServiceImpl implements ICtripBCPublicService {

    private static final String LOGIN_TICKET_URL = "https://www.corporatetravel.ctrip.com/corpservice/authorize/ticket";
    private static final String ORDER_TICKET_URL = "https://www.corporatetravel.ctrip.com/SwitchAPI/Order/Ticket";
    private static final String ORDER_URL = "https://www.corporatetravel.ctrip.com/switchapi/Order/SearchOrder";
    private static final String SETTLE_ORDER_TICKET_URL = "https://ct.ctrip.com/SwitchAPI/Order/Ticket";
    private static final String FLIGHT_ORDER_URL = "https://ct.ctrip.com/switchapi/FlightOrderSettlement/GetCorpAccountFlightOrderSettlements?type=json";
    private static final String HTL_ORDER_URL = "https://ct.ctrip.com/switchapi/SettlementHltOrder/SearchSettlementHltOrderDetail";
    private static final String TRAIN_ORDER_URL = "https://ct.ctrip.com/switchapi/SettlementTrainOrder/SearchSettlementTrainOrderDetail";
    private static final String CAR_ORDER_URL = "https://ct.ctrip.com/switchapi/CarOrderSettlement/SearchSettlementCarOrderDetail";
    public static final String CTRIP_TRAVEL = "travel";
    public static final String CTRIP_HOTEL = "hotel";

    private static Logger logger = LoggerFactory.getLogger(CtripBCPublicServiceImpl.class);

    @Value("${ybz.baseUrl}")
    private String ybzBaseUrl;

    @Value("${ybz.getMnecode.url}")
    private String getMnecode;

    @Autowired
    IBriSysConfigService briSysConfigService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Reference
    @Qualifier("ctripGroupMemberServiceImpl")
    private ICtripGroupMemberService ctripGroupMemberService;

    @Autowired
    private ICtripBCUserService ctripBCUserService;

    @Autowired
    private IThirdPropertyService thirdPropertyService;

    @Autowired
    private IBaseDocService baseDocService;

    @Autowired
    private IMongoService mongoService;

    @Override
    public String ssoMobileLogin(String employeeId, HttpServletResponse
            response, CtripBCConfig ctripBCConfig, String initPage, int tokenType) throws IOException {
        // Ticket 获取 URL
        //携程提供
        String appKey = ctripBCConfig.getAppKey();
        String appSecurity = ctripBCConfig.getAppSecurity();
        //Json 串
        String ticketPostString =
                "{\"appKey\":\"" + appKey + "\",\"appSecurity\":\"" + appSecurity + "\", \"TokenType\":" + tokenType + ", \"GroupID\":2909}";
        //POST
        String ticketResponse = sendPost(LOGIN_TICKET_URL, ticketPostString);
        //构造 JSON 对象,需要导入 net.sf.json 包
        net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                JSONSerializer.toJSON(ticketResponse);
        if (!jsonObject.optBoolean("Success")) {
            logger.error("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
            throw new RuntimeException("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
        }
        //获取 Ticket
        String token = (String) jsonObject.get("Token");
        String responseText = "<html>\n" +
                "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" >\n" +
                "<script type=\"text/javascript\">function formSubmit(){document.getElementById(\"fLogin\").submit();}</script>\n" +
                "</head>\n" +
                "<body>\n" +
                "<form name=\"fLogin\" id=\"fLogin\" action=\"http://ct.ctrip.com/m/SingleSignOn/H5SignInfo\" method=\"post\">\n" +
                "<input type=\"hidden\" name=\"accessuserid\" value=\"" + appKey + "\" />\n" +
                "<input type=\"hidden\" name=\"employeeid\" value=\"" + employeeId + "\" />\n" +
                "<input type=\"hidden\" name=\"initpage\" value=\"" + initPage + "\"/>\n" +
                "<input type=\"hidden\" name=\"appid\" value=\"" + ctripBCConfig.getCorporationId() + "\" />\n" +
                "<input type=\"hidden\" name=\"endorsementID\" value=\"\" />\n" +
                "<input type=\"hidden\" name=\"token\" value=\"" + token + "\"/>\n" +
                "<input type=\"hidden\" name=\"channel\" value=\"\"/>\n" +
                "<input type=\"hidden\" name=\"OnError\" value=\"ErrorCode\"/>\n" +
                "<script language=\"javascript\">formSubmit();</script>\n" +
                "</form>\n" +
                "</body>\n" +
                "</html>";
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println(responseText);
        return responseText;
    }
    @Override
    public String ssoPCLogin(String employeeId, HttpServletResponse response,
                             CtripBCConfig ctripBCConfig, String initPage, int tokenType) throws IOException{
        // Ticket 获取 URL
        //携程提供
        String appKey = ctripBCConfig.getAppKey();
        String appSecurity = ctripBCConfig.getAppSecurity();
        //Json 串
        String ticketPostString =
                "{\"appKey\":\"" + appKey + "\",\"appSecurity\":\"" + appSecurity + "\", \"TokenType\":" + tokenType + ", \"GroupID\":2909}";
        //POST
        String ticketResponse = sendPost(LOGIN_TICKET_URL, ticketPostString);
        //构造 JSON 对象,需要导入 net.sf.json 包
        net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                JSONSerializer.toJSON(ticketResponse);
        if (!jsonObject.optBoolean("Success")) {
            logger.error("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
            throw new RuntimeException("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
        }
        //获取 Ticket
        String token = (String) jsonObject.get("Token");
        String signature = MD5Util.getMD5_32(appKey + employeeId + "0" + MD5Util.getMD5_32(appSecurity));
        String loginUrl="https://ct.ctrip.com/corpservice/authorize/login";
        String responseText="<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"
                                +"<script type=\"text/javascript\">function formSubmit(){document.getElementById(\"fLogin\").submit();}</script>"
                                +"</head><body>"
                                +"<form name=\"fLogin\" id=\"fLogin\" method=\"post\" action=\""+loginUrl+"\">"
                                +"<input type=\"hidden\" name=\"AppKey\" value=\""+appKey+"\" />"
                                +"<input type=\"hidden\" name=\"Ticket\" value=\""+token+"\" />"
                                +"<input type=\"hidden\" name=\"EmployeeID\" value=\""+employeeId+"\"/>"
                                +"<input type=\"hidden\" name=\"Signature\" value=\""+ signature +"\"/>"
                                +"<input type=\"hidden\" name=\"TA\" value=\"\"/>"
                                +"<script language=\"javascript\">formSubmit();</script></form></body>";
        //设置编码为UTF-8
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        PrintWriter pw = response.getWriter();
        pw.println(responseText);
        return responseText;
    }

    @Override
    public boolean syncCtripBCUsers(List<CtripBCUser> ctripBCUsers, CtripBCConfig config, BriChannel briChannel) {
        String appKey = config.getAppKey();
        String appSecurty = config.getAppSecurity();
        String corporationId = config.getCorporationId();
        String subAccountName = config.getSubAccountName();
        String tenantId = ctripBCUsers.get(0).getTenant();
        OrderSearchTicketResponse ticketResponse = CorpTicketService.getEmployeeSyncTicket(appKey, appSecurty, "1.0");
        if (ticketResponse != null && ticketResponse.getStatus() != null && ticketResponse.getStatus().getSuccess()) {
            logger.info("get ticket success! ticket:" + ticketResponse.getTicket());
            boolean flag = Boolean.TRUE;
            AuthenticationListRequst authenticationListRequst = new AuthenticationListRequst();
            authenticationListRequst.setTicket(ticketResponse.getTicket());
            authenticationListRequst.setCorporationID(corporationId);
            authenticationListRequst.setAppkey(appKey);
            // 与已同步的人员进行对比，找到未同步及有改动的人员信息
            JSONObject result = ctripBCUserService.getCtripBCUsersNeedSync(ctripBCUsers, config, tenantId);
            List<CtripBCUser> ctripBCUsersNeedInsert = JSONObject.parseArray(JSON.toJSONString(result.getJSONArray("ctripBCUsersNeedInsert")), CtripBCUser.class);
            List<CtripBCUser> ctripBCUsersNeedUpdate = JSONObject.parseArray(JSON.toJSONString(result.getJSONArray("ctripBCUsersNeedUpdate")), CtripBCUser.class);
            List<List<CtripBCUser>> listNeedInsert = ListUtils.partition(ctripBCUsersNeedInsert, 500);
            List<List<CtripBCUser>> listNeedUpdate = ListUtils.partition(ctripBCUsersNeedUpdate, 500);
            if (!CollectionUtils.isEmpty(listNeedInsert)) {
                flag = isFlag(briChannel, subAccountName, tenantId, flag, authenticationListRequst, listNeedInsert, "insert");
            }
            if (!CollectionUtils.isEmpty(listNeedUpdate)) {
                flag = isFlag(briChannel, subAccountName, tenantId, flag, authenticationListRequst, listNeedUpdate, "update");
            }
            return flag;
        } else {
            String errorms = String.format("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            logger.info("get ticket failed! error message:{}", JSON.toJSONString(ticketResponse));
            throw new RuntimeException(errorms);
        }
    }

    private boolean isFlag(BriChannel briChannel, String subAccountName, String tenantId, boolean flag, AuthenticationListRequst authenticationListRequst, List<List<CtripBCUser>> listNeedSync, String operateType) {
        for (List<CtripBCUser> ctripUserBatch : listNeedSync) {
            //特殊人员userIdList
            List<String> specialUserIdList = this.getSpecialUserIdList(ctripUserBatch, tenantId);
            List<AuthenticationInfoList> authenticationInfoLists = new ArrayList<>();
            for (CtripBCUser ctripBCUser : ctripUserBatch) {
                //特殊人员不进行同步
                if (specialUserIdList.contains(ctripBCUser.getUserId())) {
                    continue;
                }
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("subAccountName" , subAccountName);
                Authentication authencationEntity = getAuthentication(ctripBCUser, jsonObject, briChannel);
                AuthenticationInfoList authenticationInfoList = new AuthenticationInfoList();
                authenticationInfoList.setAuthentication(authencationEntity);
                authenticationInfoList.setSequence("0");
                authenticationInfoLists.add(authenticationInfoList);
            }
            authenticationListRequst.setAuthenticationInfoList(authenticationInfoLists);
            if (!multipleUsersSync(authenticationListRequst)) {
                flag = Boolean.FALSE;
            } else {
                if ("insert".equals(operateType)) {
                    ctripBCUserService.insertBatch(ctripUserBatch);
                } else if ("update".equals(operateType)) {
                    ctripBCUserService.updateBatchById(ctripUserBatch);
                }
            }
        }
        return flag;
    }

    /**
     * 查询特殊人员设置判断是否需要更新
     *
     * @param ctripBCUserList   用户列表
     * @param tenantId          租户ID
     * @return List<String> 特殊人员userId List
     */
    private List<String> getSpecialUserIdList(List<CtripBCUser> ctripBCUserList, String tenantId) {
        List<String> userIdList = new ArrayList<>();
        ctripBCUserList.forEach(ctripBCUser -> userIdList.add(ctripBCUser.getUserId()));
        List<CtripGroupMember> ctripGroupMemberList;
        List<String> specialMemberUserIdList = new ArrayList<>();
        try{
            Wrapper<CtripGroupMember> wrapper = new EntityWrapper<>();
            wrapper.in(CtripGroupMember.USERID, userIdList);
            InvocationInfoProxy.setTenantid(tenantId);
            ctripGroupMemberList = ctripGroupMemberService.selectList(wrapper);
        } catch (Exception e) {
            logger.error("YBZ特殊人员设置查询异常不更新，异常信息{}", e.getMessage());
            //调用失败的话就所有都不同步
            return userIdList;
        }
        ctripGroupMemberList.forEach(ctripUser -> {
            specialMemberUserIdList.add(ctripUser.getUserid());
        });
        return specialMemberUserIdList;
    }

    public static boolean multipleUsersSync(AuthenticationListRequst authenticationListRequst) {
        AuthenticationInfoListResponse authenticationInfoListResponse;
        MultipleEmployeeSyncService empoyeeSyncService = new MultipleEmployeeSyncService();
        logger.info("ctripBC syncUser param : " + JSON.toJSONString(authenticationListRequst));
        authenticationInfoListResponse = empoyeeSyncService.MultipleEmployeeSync(authenticationListRequst);
        if (authenticationInfoListResponse != null) {
            String result = authenticationInfoListResponse.getResult();
            if ("Failed".equals(result)) {
                List<ErrorMessage> errorMessages = authenticationInfoListResponse.getErrorMessageList();
                if (!errorMessages.isEmpty()) {
                    for (ErrorMessage errorMessage : errorMessages) {
                        logger.info(JSONObject.toJSONString(errorMessage));
                    }
                }
                return false;
            }
            logger.info(authenticationInfoListResponse.getResult());
            return true;
        }
        return false;
    }


//    private static List<Authentication> getAuthentications(List<CtripBCUser> ctripBCUsers) {
//        List<Authentication> authentications = new ArrayList<>();
//        if (ctripBCUsers != null && ctripBCUsers.size() > 0) {
//            for (int i = 0; i < ctripBCUsers.size(); i++) {
//                authentications.add(getAuthentication(ctripBCUsers.get(i)));
//            }
//        }
//        return authentications;
//    }

    private static Authentication getAuthentication(CtripBCUser ctripBCUser, BriChannel briChannel) {
        Authentication authencationEntity = new Authentication();
        authencationEntity.setEmployeeID(ctripBCUser.getEmployeeId());
        authencationEntity.setCorporationID(ctripBCUser.getCorporationID());
        authencationEntity.setName(ctripBCUser.getName());
        authencationEntity.setEmail(ctripBCUser.getEmail());
        authencationEntity.setMobilePhone(ctripBCUser.getMobilePhone());
//        if (!StringUtil.isEmpty(ctripBCUser.getEmail())) {
//            authencationEntity.setIsSendEMail(true);
//        } else {
//            authencationEntity.setIsSendEMail(false);
//        }
        //不发送邮件
        authencationEntity.setIsSendEMail(false);
        //在职情况 (A-在职,I-离职)
        authencationEntity.setValid(ctripBCUser.getValid());
        if (!StringUtil.isEmpty(ctripBCUser.getDept1())) {
            authencationEntity.setDept1(ctripBCUser.getDept1());
        }
        authencationEntity.setDept2(ctripBCUser.getDept2());
        if (BriChannel.SYNCRANK == briChannel.getSyncRank()) {
            authencationEntity.setRankName(ctripBCUser.getRankName());
        }
        authencationEntity.setIsBookClass(ctripBCUser.getIsBookClass());
        authencationEntity.setIntlBookClassBlock(ctripBCUser.getIntlBookClassBlock());
        authencationEntity.setResRange(ctripBCUser.getResRange());
        if (ctripBCUser.getUseTRFlag() != null) {
            authencationEntity.setUseTRFlag(ctripBCUser.getUseTRFlag().intValue());
        }
        authencationEntity.setCorpCardType(ctripBCUser.getCorpCardType());

        authencationEntity.setDept3("");

        authencationEntity.setSubAccountName(ctripBCUser.getSubaccountName());

        return authencationEntity;
    }

    private static Authentication getAuthentication(CtripBCUser ctripBCUser , JSONObject jsonObject, BriChannel briChannel){
        Authentication authencationEntity = getAuthentication(ctripBCUser, briChannel);
        String subAccountName = jsonObject.getString("subAccountName");
        authencationEntity.setSubAccountName(subAccountName);
        return  authencationEntity;
    }
    private static Authentication getAuthentication(CtripBCUser ctripBCUser , JSONObject jsonObject , String email, BriChannel briChannel){
        Authentication authencationEntity = getAuthentication(ctripBCUser , jsonObject, briChannel);
        authencationEntity.setConfirmPerson2(email);
        return authencationEntity;
    }


    @Override
    public String doRMIOrdersSearch(String startDate, String endDate, CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip RMI: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");
            String postString = "{\"request\": {\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"JourneyNo\": \"\",\"OrderID\":\"\",\"EID\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"SearchType\": \"1\",\"Version\": \"\"}}";
            orderResults = sendPost(ORDER_URL, postString);
            logger.info("ctripbc pull order result:" + orderResults);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程订单失败！", e);
            return null;
        }

    }

    @Override
    public String SearchSettlementFlightOrder(String startDate, String endDate,CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(SETTLE_ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip Settlement: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip Settlement: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");
            String postString = "{\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"AccountID\": \"\",\"OrderID\":\"\",\"RecordID\":\"\",\"BatchNo\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"IsCompensation\": true,\"PayType\": \"All\"}";
            orderResults = sendPost(FLIGHT_ORDER_URL, postString);
            logger.info("ctripbc pull settlementFlightOrder result:" + orderResults);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程机票结算数据失败！" + e.getMessage(), e);
            return null;
        }
    }


    @Override
    public String SearchSettlementHtlOrder(String startDate, String endDate, CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(SETTLE_ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip Settlement: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip Settlement: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");

            String postString = "{\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"AccountID\": \"\",\"OrderID\":\"\",\"RecordID\":\"\",\"BatchNo\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"IsCompensation\": true}";
            orderResults = sendPost(HTL_ORDER_URL, postString);

            logger.info("ctripbc pull order result:" + orderResults);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程酒店结算数据失败！", e);
            return null;
        }
    }

    @Override
    public String SearchSettlementTrainOrder(String startDate, String endDate, CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(SETTLE_ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip Settlement: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip Settlement: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");

            String postString = "{\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"AccountID\": \"\",\"OrderID\":\"\",\"RecordID\":\"\",\"BatchNo\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"IsCompensation\": true}";
            orderResults = sendPost(TRAIN_ORDER_URL, postString);

            logger.info("ctripbc pull order result:" + orderResults);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程订单失败！", e);
            return null;
        }
    }


    @Override
    public String SearchSettlementCarOrder(String startDate, String endDate, CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(SETTLE_ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip Settlement: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip Settlement: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");

            String postString = "{\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"AccountID\": \"\",\"OrderID\":\"\",\"RecordID\":\"\",\"BatchNo\":\"\",\"DateFrom\": \""
                    + startDate + "\",\"DateTo\": \"" + endDate + "\",\"IsCompensation\": true}";
            orderResults = sendPost(CAR_ORDER_URL, postString);

            logger.info("ctripbc pull order result:" + orderResults);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程订单失败！", e);
            return null;
        }
    }




    /**
     * 按照订单号和产品类别拉取订单
     *
     * @param searchType    产品类别 1：机票、酒店、火车票、用车、马上用车 2：机票 3：火车票 4：酒店 5：用车（包含老版国内接送机、国际接送机、国内租车） 6：马上用车 7：新版国内接送机 8：国内包车
     * @param orderIds      订单号
     * @param ctripBCConfig 客户携程配置信息
     * @since 2019-01-26
     */
    @Override
    public String doOrdersSearch(String searchType, String orderIds, CtripBCConfig ctripBCConfig) {
        String orderResults;
        try {
            String params = "{\"appKey\":\"" + ctripBCConfig.getAppKey() + "\",\"appSecurity\":\"" + ctripBCConfig.getAppSecurity() + "\"}";
            String ticketResponse = sendPost(ORDER_TICKET_URL, params);
            //构造 JSON 对象,需要导入 net.sf.json 包
            net.sf.json.JSONObject jsonObject = (net.sf.json.JSONObject)
                    JSONSerializer.toJSON(ticketResponse);
            net.sf.json.JSONObject statusObject = jsonObject.optJSONObject("Status");
            if (!statusObject.optBoolean("Success")) {
                logger.error("Cannot call ctrip RMI: " + statusObject.optString("Message"));
                throw new RuntimeException("Cannot call ctrip RMI: " + jsonObject.optString("Message"));
            }
            String ticket = jsonObject.optString("Ticket");
            String postString = "{\"request\": {\"Auth\": {\"AppKey\": \"" + ctripBCConfig.getAppKey() + "\", \"Ticket\":\"" + ticket + "\"},\"JourneyNo\": \"\",\"OrderID\":\"" + orderIds + "\",\"EID\":\"\",\"DateFrom\": \"\", \"DateTo\": \"\",\"SearchType\": \"" + searchType + "\",\"Version\": \"\"}}";
            orderResults = sendPost(ORDER_URL, postString);
            return orderResults;
        } catch (Exception e) {
            logger.error("获取携程订单失败！", e);
            return null;
        }
    }

    @Override
    public JSONObject pushApplayOrder(BriChannel channel, String tenant, String orgPk, JSONObject applyOrderJson, boolean isOpenApi) {
        JSONObject config = JSONObject.parseObject(channel.getConfig());
        JSONObject summaryResult = new JSONObject();
        logger.info("携程申请单原始信息:" + applyOrderJson.toString());
        //获取Ticket
        logger.info("开始获取携程ticket数据！");
        summaryResult.put("success", false);
        TicketResponse ticketResponse = CorpTicketService.getOrderAuditTicket(config.getString("appKey"), config.getString("appSecurity"), "1.0");
        if (null != ticketResponse && null != ticketResponse.getStatus() && ticketResponse.getStatus().getSuccess()) {
            SetApprovalRequest setApprovalRequest = processApplyData(channel, applyOrderJson, tenant, config.getString("appKey"), ticketResponse.getTicket(), isOpenApi);
            logger.info("拼装同步申请单数据，拼装结果：" + JSON.toJSONString(setApprovalRequest));
            if (setApprovalRequest != null) {
                SetApprovalServiceRequest setApprovalServiceRequest = new SetApprovalServiceRequest();
                SetApprovalService setapprovalService = new SetApprovalService();
                // 审批
                setApprovalServiceRequest.setRequest(setApprovalRequest);
                SetApprovalResponse setApprovalResponse = setapprovalService.SetApproval(setApprovalServiceRequest);
                if (null != setApprovalResponse && null != setApprovalResponse.getStatus() && setApprovalResponse.getStatus().getSuccess()) {
                    // 审批通过，更新申请单据状态
                    summaryResult.put("success", true);
                    logger.info("向携程推送数据:推送数据成功");
                } else {
                    logger.info("向携程推送数据:调用提前审批接口失败！{}", JSON.toJSONString(setApprovalResponse));
                    summaryResult.put("msg", "向携程推送数据:调用提前审批接口失败！" + JSON.toJSONString(setApprovalResponse));
                    mongoService.saveApplyResultToMongo(tenant, channel.getChannel(), applyOrderJson, summaryResult);
                }
            } else {
                summaryResult.put("msg", "拼装同步申请单数据失败");
                mongoService.saveApplyResultToMongo(tenant, channel.getChannel(), applyOrderJson, summaryResult);
            }
        } else {
            logger.info("向携程推送数据:获取携程ticket数据失败！");
            summaryResult.put("msg", "向携程推送数据:获取携程ticket数据失败！");
            mongoService.saveApplyResultToMongo(tenant, channel.getChannel(), applyOrderJson, summaryResult);
        }
        return summaryResult;
    }

    @Override
    public List closeApplyOrder(BriChannel channel ,JSONObject trip) {
        String channelConfig = channel.getConfig();
        JSONArray result = new JSONArray();
        JSONObject res = new JSONObject();
        JSONObject config = JSONObject.parseObject(channelConfig);
        TicketResponse ticketResponse = CorpTicketService.getOrderAuditTicket(config.getString("appKey"), config.getString("appSecurity"), "1.0");
        if(ticketResponse!=null&&ticketResponse.getStatus()!=null&&ticketResponse.getStatus().getSuccess()){
            SetApprovalRequest setApprovalRequest = processApplyData(channel, trip, channel.getTenant(), config.getString("appKey"), ticketResponse.getTicket(), false);
            SetApprovalService setapprovalService=new SetApprovalService();
            SetApprovalServiceRequest setApprovalServiceRequest=new SetApprovalServiceRequest();
            setApprovalRequest.setStatus(0);
            setApprovalServiceRequest.setRequest(setApprovalRequest);
            SetApprovalResponse setApprovalResponse=setapprovalService.SetApproval(setApprovalServiceRequest);
            if(setApprovalResponse!=null&&setApprovalResponse.getStatus()!=null) {
                res.put("success", true);
                logger.info("向携程推送数据:推送数据成功");
            }else {
                logger.info("向携程推送数据:调用提前审批接口失败！{}", JSON.toJSONString(setApprovalResponse));
                res.put("success" , false);
                res.put("msg", "向携程推送数据:调用提前审批接口失败！" );
            }
        }else {
            logger.info("向携程推送数据:获取携程ticket数据失败！");
            res.put("success" , false);
            res.put("msg", "向携程推送数据:获取携程ticket数据失败！");
        }
        result.add(res);
        return result;
    }

    /**
     * 批量同步人员到携程大客户
     * @param tenantId
     * @param orgPk
     * @param openType
     * @param briChannel
     */
    @Override
    public boolean syncAllUsersToCtripBC(String tenantId, String orgPk, Integer openType, BriChannel briChannel) {
        CtripBCConfig ctripBCConfig = JSONObject.parseObject(briChannel.getConfig(), CtripBCConfig.class);
        List<ThirdProperty> thirdProperties = thirdPropertyService.getThirdPropertyByTenantOrgChannel(tenantId, orgPk, briChannel.getChannel());
        List<UcUserDto> ucUserList = new CopyOnWriteArrayList<>();
        //1.获取所有用户
        if (OpenTypeEnum.TENTANT.getIndex() == openType) {
            ucUserList = iUserCenterService.getUcUsersByTenantId(tenantId);
        } else if ((OpenTypeEnum.ORG.getIndex() == openType)) {
            ucUserList = iUserCenterService.getUcUserDtoByOrg(tenantId, orgPk);
        }
        //2.转化为CtripBCUser
        List<CtripBCUser> ctripBCUsers = CtripBCUserConvertUtil.getCtripBCUser(ucUserList, ctripBCConfig.getCorporationId(), tenantId, "", thirdProperties, briChannel);
        //3.同步用户到携程
        return this.syncCtripBCUsers(ctripBCUsers, ctripBCConfig, briChannel);
    }

    /**
     * 申请单数据处理
     *
     * @param applyOrderJson 申请单信息
     * @param tenant         租户ID
     * @param appKey         appKey
     * @param ticket         认证信息
     * @return {@link SetApprovalRequest}   推送携程申请单信息
     */
    private SetApprovalRequest processApplyData(BriChannel channel, JSONObject applyOrderJson, String tenant, String appKey, String ticket, boolean isOpenApi) {
        JSONObject nodeBusinessTrip = applyOrderJson;
        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        String openType = special.getString("openType");
        SetApprovalRequest setApprovalRequest = new SetApprovalRequest();
        if (StringUtil.isNotEmpty(nodeBusinessTrip.getString("billNum"))) {
            setApprovalRequest.setApprovalNumber(nodeBusinessTrip.getString("billNum"));
        } else {
            setApprovalRequest.setApprovalNumber(special.getString("applayNumber"));
        }
        // 审批状态 0：无效1：有效
        setApprovalRequest.setStatus(1);
        // 员工ID
        String userId = nodeBusinessTrip.getString("userId");
        UcUserDto ucUser = null;
        if (isOpenApi) {
            //ncc传的是手机号
            ucUser = iUserCenterService.getCompleteUcUserDtoByPhone(userId, tenant);
            if (ucUser == null) {
                logger.info("用户中心找不到用户tenantId:" + tenant + " phone:" + userId);
                return null;
            }
        } else {
            List<String> list = new ArrayList<>();
            list.add(userId);
            List<UcUserDto> users = iUserCenterService.getCompleteUcUserDtoByUserid(list, tenant);
            // 员工编号
            if (users != null && users.size() > 0) {
                ucUser = users.get(0);
            } else {
                logger.info("用户中心找不到用户tenantId:" + tenant + " userid:" + userId);
                //TODO 用户中心未找到用户时同步erp用户并重试
                return null;
            }
        }
        setApprovalRequest.setEmployeeID(ucUser.getPersonCode());
        //费用承担信息
        processCostInfo(tenant, userId, openType, setApprovalRequest, channel, nodeBusinessTrip);

        // 认证信息
        Authentification authInfo = new Authentification(appKey, ticket);
        setApprovalRequest.setAuth(authInfo);
        // 审批单过期时间
        Calendar c = Calendar.getInstance();
        c.setTime(nodeBusinessTrip.getDate("endDate"));
        c.add(Calendar.DAY_OF_MONTH, 1);
        Format f = new SimpleDateFormat("yyyy-MM-dd");
        Date expiredTime = c.getTime();
        setApprovalRequest.setExpiredTime(f.format(expiredTime));
        logger.info(setApprovalRequest.getApprovalNumber() + ":expire:" + f.format(expiredTime));
        // 飞机信息
        ArrayList<FlightEndorsementDetail> flightEndorsementDetails = new ArrayList<>();
        // 火车信息
        ArrayList<TrainEndorsementDetail> trainEndorsementDetails = new ArrayList<>();
        // 住宿
        ArrayList<HotelEndorsementDetail> hotelEndorsementDetails = new ArrayList<>();
        // 及时用车
        ArrayList<CarQuickEndorsementDetail> carQuickEndorsementDetails = new ArrayList<>();
        // 接送（火车、飞机）用车
        ArrayList<CarPickUpEndorsementDetail> carPickUpEndorsementDetail = new ArrayList<>();

        // 单据详情
        JSONArray travelList = nodeBusinessTrip.getJSONArray("nodeBusinessTravelList");
        if (null != travelList && travelList.size() > 0) {
            flightEndorsementDetails = getFlightInfos(travelList, nodeBusinessTrip, ucUser.getPersonCode(), tenant, openType, channel);
            trainEndorsementDetails = getTrainInfos(travelList, nodeBusinessTrip, ucUser.getPersonCode(), tenant, openType, channel);
            hotelEndorsementDetails = getHotelInfos(travelList, nodeBusinessTrip, ucUser.getPersonCode(), tenant, openType, channel);

            carQuickEndorsementDetails = getQuickCarInfo(travelList, nodeBusinessTrip, ucUser.getPersonCode(), tenant, openType, channel);
            carPickUpEndorsementDetail = getPickUpCarInfo(travelList, nodeBusinessTrip, ucUser.getPersonCode(), tenant, openType, channel);

        }
        // 飞机信息
        if (null != flightEndorsementDetails && flightEndorsementDetails.size() > 0) {
            setApprovalRequest.setFlightEndorsementDetails(flightEndorsementDetails);
        }
        // 火车信息
        if (null != trainEndorsementDetails && trainEndorsementDetails.size() > 0) {
            setApprovalRequest.setTrainEndorsementDetails(trainEndorsementDetails);
        }
        // 住宿
        if (null != hotelEndorsementDetails && hotelEndorsementDetails.size() > 0) {
            setApprovalRequest.setHotelEndorsementDetails(hotelEndorsementDetails);
        }
        //及时用车
        if (null != carQuickEndorsementDetails && carQuickEndorsementDetails.size() > 0) {
            setApprovalRequest.setCarQuickEndorsementDetails(carQuickEndorsementDetails);
        }
        // 接送（火车、飞机）用车
        if (null != carPickUpEndorsementDetail && carPickUpEndorsementDetail.size() > 0){
            setApprovalRequest.setCarPickUpEndorsementDetails(carPickUpEndorsementDetail);
        }

        if (CollectionUtils.isEmpty(flightEndorsementDetails) && CollectionUtils.isEmpty(trainEndorsementDetails) && CollectionUtils.isEmpty(hotelEndorsementDetails)) {
            logger.info("向携程推送数据:飞机、火车、酒店数据为空、推送数据失败！");
            return null;
        }
        //是否需要传职级POST_NAME
        // 0不传 1制单人职级 2申请人职级
        Integer rankSecondPass = channel.getRankSecondPass();
        String postName = "";
        if (isOpenApi) {
            postName = applyOrderJson.getString("rankName");
        } else {
            switch (rankSecondPass){
                case 0:
                    break;
                case 1:
                    postName = ucUser.getPostName();
                    break;
                case 2:
                    String defitem30 = applyOrderJson.getString("defitem30");
                    String applyUserId = applyOrderJson.getString("applyUser");
                    if (StringUtils.isNotEmpty(defitem30)) {
                        postName = defitem30;
                    } else {
                        if (userId.equals(applyUserId)){
                            postName = ucUser.getPostName();
                        } else {
                            if ("saas".equals(openType)){
                                if (isOpenApi) {
                                    UcUserDto ucUserDto = iUserCenterService.getCompleteUcUserDtoByPhone(applyUserId, tenant);
                                    postName = ucUserDto != null ? ucUserDto.getPostName() : postName;
                                } else {
                                    List<UcUserDto> applyUser = iUserCenterService.getCompleteUcUserDtoByUserid(Collections.singletonList(applyUserId), tenant);
                                    if (applyUser != null && applyUser.size() > 0) {
                                        postName = applyUser.get(0).getPostName();
                                    }
                                }
                            } else {
                                //apply_user中的值可能是personid
                                List<UcUserDto> applyUser = iUserCenterService.getCompleteUcUserByPersonIds(Collections.singletonList(applyUserId), tenant);
                                if (applyUser != null && applyUser.size() > 0){
                                    postName = applyUser.get(0).getPostName();
                                }else {
                                    if (isOpenApi) {
                                        UcUserDto ucUserDto = iUserCenterService.getCompleteUcUserDtoByPhone(applyUserId, tenant);
                                        postName = ucUserDto != null ? ucUserDto.getPostName() : postName;
                                    } else {
                                        applyUser = iUserCenterService.getCompleteUcUserDtoByUserid(Collections.singletonList(applyUserId), tenant);
                                        if (applyUser != null && applyUser.size() > 0) {
                                            postName = applyUser.get(0).getPostName();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;
                default:
                    break;
            }
        }
        if (StringUtil.isNotEmpty(postName)){
            RankInfo rankInfo = new RankInfo();
            rankInfo.setRankName(postName);
            setApprovalRequest.setRankInfo(rankInfo);
        }
        return setApprovalRequest;
    }

    /**
     * 接送（火车、飞机）用车
     * @param travelList
     * @param nodeBusinessTrip
     * @param personCode
     * @param tenant
     * @param openType
     * @param channel
     * @return
     */
    private ArrayList<CarPickUpEndorsementDetail> getPickUpCarInfo(JSONArray travelList, JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel channel) {
        ArrayList<CarPickUpEndorsementDetail> pickUpList = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        JSONObject cityCodeMap = special.getJSONObject("cityCodes");

        //实际出行人
        ArrayList<PassengerDetail> passengerList = getPassengers(nodeBusinessTrip, personCode, tenant, openType, channel);

        Map<String, Set<String>> detailCityMap = new HashMap<>();
        for (int i = 0; i < travelList.size(); i++) {
            JSONObject travel = travelList.getJSONObject(i);
            String trafficCity = StringUtils.isNotEmpty(travel.getString("defitem30")) ? travel.getString("defitem30") : travel.getString("trafficCity");
            String trafficType = StringUtils.isNotEmpty(travel.getString("defitem31")) ? travel.getString("defitem31") : travel.getString("trafficType");
            if (trafficType == null){
                continue;
            }
            String tripWay = travel.getString("tripWay");
            if ("网约车".equals(tripWay) && !"21".equals(trafficType) && !"10".equals(trafficType)) {
                if (detailCityMap.containsKey(trafficType)){
                    detailCityMap.get(trafficType).add(cityCodeMap.getString(trafficCity));
                }else {
                    Set<String> citySet = new HashSet<>();
                    citySet.add(cityCodeMap.getString(trafficCity));
                    detailCityMap.put(trafficType, citySet);
                }
            }


        }
        for (String key : detailCityMap.keySet()) {
            CarPickUpEndorsementDetail pickUpDetail = new CarPickUpEndorsementDetail();
            pickUpDetail.setPassengerList(passengerList);
            Integer patternType = Integer.valueOf(key);
            pickUpDetail.setProductType(6);
            pickUpDetail.setPatternType(patternType);
            if (detailCityMap.get(key) != null && detailCityMap.get(key).size() > 0){
                pickUpDetail.setCities(String.join(",", detailCityMap.get(key)));
            }
            String beginDate = sf.format(nodeBusinessTrip.getDate("startDate"));
            String endDate = sf.format(nodeBusinessTrip.getDate("endDate"));

            pickUpDetail.setPickUpBeginDate(beginDate);
            pickUpDetail.setPickUpEndDate(endDate);
            pickUpDetail.setDropOffBeginDate(beginDate);
            pickUpDetail.setDropOffEndDate(endDate);
            pickUpList.add(pickUpDetail);
        }

        return pickUpList;
    }

    /**
     * 及时用车
     * @param travelList
     * @param nodeBusinessTrip
     * @param personCode
     * @param tenant
     * @param openType
     * @param channel
     * @return
     */
    private ArrayList<CarQuickEndorsementDetail> getQuickCarInfo(JSONArray travelList, JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel channel) {
        ArrayList<CarQuickEndorsementDetail> quickList = new ArrayList<>();
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        JSONObject cityCodeMap = special.getJSONObject("cityCodes");
        //实际出行人
        ArrayList<PassengerDetail> passengerList = getPassengers(nodeBusinessTrip, personCode, tenant, openType, channel);
        Set<String> cityList = new HashSet<>();
        for (int i = 0; i < travelList.size(); i++) {
            JSONObject travel = travelList.getJSONObject(i);
            String tripWay = travel.getString("tripWay");
            String trafficCity = StringUtils.isNotEmpty(travel.getString("defitem30")) ? travel.getString("defitem30") : travel.getString("trafficCity");
            String trafficType = StringUtils.isNotEmpty(travel.getString("defitem31")) ? travel.getString("defitem31") : travel.getString("trafficType");

            if ("网约车".equals(tripWay) && "10".equals(trafficType)){
                cityList.add(cityCodeMap.getString(trafficCity));
            }
        }
        CarQuickEndorsementDetail quickDetail = new CarQuickEndorsementDetail();
        String beginDate = sf.format(nodeBusinessTrip.getDate("startDate"));
        String endDate = sf.format(nodeBusinessTrip.getDate("endDate"));
        quickDetail.setBeginUseDate(beginDate);
        quickDetail.setEndUseDate(endDate);
        quickDetail.setPassengerList(passengerList);
        quickDetail.setProductType(10);
        if (cityList.size() > 0){
            quickDetail.setCities(String.join(",", cityList));
        }
        quickList.add(quickDetail);

        return quickList;
    }


    /**
     * 同步费用归属信息
     * @param tenant
     * @param userId
     * @param openType
     * @param setApprovalRequest
     * @param channel
     * @param nodeBusinessTrip
     */
    private void processCostInfo(String tenant, String userId, String openType, SetApprovalRequest setApprovalRequest, BriChannel channel, JSONObject nodeBusinessTrip) {
        if (channel != null && channel.getSyncCostInfo() != 0) {
            //费用承担部门
            String assumeDept = nodeBusinessTrip.getString("assumeDept");
            String[] assumeDeptArr = assumeDept != null ? assumeDept.split(",") : null;

            //费用承担单位
            String assumeOrg = nodeBusinessTrip.getString("assumeOrg");
            String[] assumeOrgArr = assumeOrg != null ? assumeOrg.split(",") : null;

            //费用项目
            String costProject = nodeBusinessTrip.getString("costProject");
            String[] costProjectArr = costProject != null ? costProject.split(",") : null;

            String assumeDeptValue = "";
            String assumeOrgValue = "";
            String assumeProjectValue = "";
            JSONObject paramJSON = new JSONObject();
            paramJSON.put("tenantId", tenant);
            paramJSON.put("userId", userId);
            switch (channel.getSyncCostInfo()) {
                //传名称
                case 1:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        if (assumeDeptArr.length > 1){
                            assumeDeptValue = assumeDeptArr[1];
                        }else {
                            Map<String, String> deptInfo = baseDocService.getDeptByOsType(tenant, userId ,assumeDeptArr[0], openType);
                            assumeDeptValue = deptInfo != null ? deptInfo.get("name") : "";
                        }
                    }

                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        if (assumeOrgArr.length > 1) {
                            assumeOrgValue = assumeOrgArr[1];
                        }else {
                            Map<String, String> orgInfo = baseDocService.getOrgByOsType(tenant, userId, assumeOrgArr[0], openType);
                            assumeOrgValue = orgInfo != null ? orgInfo.get("name") : "";
                        }
                    }

                    if (costProjectArr != null && costProjectArr.length > 0){
                        if (costProjectArr.length > 1){
                            assumeProjectValue = costProjectArr[1];
                        }else {
                            Map<String, String> projectInfo = baseDocService.getInOutProjectByOsType(tenant, userId, costProjectArr[0], openType);
                            assumeProjectValue = projectInfo != null ? projectInfo.get("name") : "";
                        }
                    }
                    break;
                //传pk
                case 2:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        assumeDeptValue = assumeDeptArr[0];
                    }

                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        assumeOrgValue = assumeOrgArr[0];
                    }

                    if (costProjectArr != null && costProjectArr.length > 0){
                        assumeProjectValue = costProjectArr[0];
                    }
                    break;
                case 3:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        assumeDeptValue = assumeDeptArr[0];
                        paramJSON.put("pk", assumeDeptValue);
                        paramJSON.put("docType", "dept");
                        String resultStr = HttpClientUtil.doPostJson(ybzBaseUrl + getMnecode + "?tenantId=" + tenant, JSON.toJSONString(paramJSON));
                        if (StringUtils.isNotEmpty(resultStr)) {
                            try {
                                JSONObject resultJSON = JSONObject.parseObject(resultStr);
                                if (resultJSON != null && resultJSON.getJSONObject("baseDocResult") != null) {
                                    String name = resultJSON.getJSONObject("baseDocResult").getString("name");
                                    String mnecode = resultJSON.getJSONObject("baseDocResult").getString("mnecode");
                                    assumeDeptValue = mnecode + " " + name;
                                }
                            } catch (Exception e) {
                                logger.error("getMnecode error : " + e.getMessage());
                            }
                        } else {
                            logger.error("getMnecode result is null, param: " + JSON.toJSONString(paramJSON));
                        }
                    }

                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        if (assumeOrgArr.length > 1) {
                            assumeOrgValue = assumeOrgArr[1];
                        }else {
                            Map<String, String> orgInfo = baseDocService.getOrgByOsType(tenant, userId, assumeOrgArr[0], openType);
                            assumeOrgValue = orgInfo != null ? orgInfo.get("name") : "";
                        }
                    }

                    if (costProjectArr != null && costProjectArr.length > 0){
                        Map<String, String> projectInfo = baseDocService.getInOutProjectByOsType(tenant, userId, costProjectArr[0], openType);
                        assumeProjectValue = projectInfo != null ? projectInfo.get("code") + " " + projectInfo.get("name") : "";
                    }
                    break;
                default:
                    break;
            }
            ArrayList<ExtendField> extendFields = new ArrayList<>();
            if (assumeOrgArr != null && assumeOrgArr.length > 0 && StringUtils.isNotEmpty(assumeOrgValue) && StringUtils.isNotEmpty(assumeOrgArr[0])) {
                ExtendField orgField = new ExtendField();
                orgField.setFieldName("CostCenter1");
                orgField.setFieldType("String");
                orgField.setFieldValue(assumeOrgValue);
                extendFields.add(orgField);
            }

            if (assumeDeptArr != null && assumeDeptArr.length > 0 && StringUtils.isNotEmpty(assumeDeptValue) && StringUtils.isNotEmpty(assumeDeptArr[0])) {
                ExtendField deptField = new ExtendField();
                deptField.setFieldName("CostCenter2");
                deptField.setFieldType("String");
                deptField.setFieldValue(assumeDeptValue);
                extendFields.add(deptField);
            }
            if (costProjectArr != null && costProjectArr.length > 0 && StringUtils.isNotEmpty(assumeProjectValue) && StringUtils.isNotEmpty(costProjectArr[0])) {
                ExtendField projectField = new ExtendField();
                projectField.setFieldName("CostCenter3");
                projectField.setFieldType("String");
                projectField.setFieldValue(assumeProjectValue);
                extendFields.add(projectField);
            }
            if (extendFields.size() > 0) {
                setApprovalRequest.setExtendFieldList(extendFields);
            }
        }
    }

    /**
     * 酒店信息组装
     *
     * @param travelList       申请单行程明细
     * @param nodeBusinessTrip 申请单信息
     * @param personCode       员工编号
     * @param tenant           租户ID
     * @param openType         NC还是SAAS
     * @param channel
     * @return {@link HotelEndorsementDetail} 携程审批单酒店信息
     */
    private ArrayList<HotelEndorsementDetail> getHotelInfos(JSONArray travelList, JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel channel) {
        logger.info("向携程推送数据:组织住宿数据！");
        ArrayList<HotelEndorsementDetail> hotelEndorsementDetails = new ArrayList<>();
        HotelEndorsementDetail hotelEndorsementDetail = new HotelEndorsementDetail();
        // 入住日期
        hotelEndorsementDetail.setCheckInBeginDate(nodeBusinessTrip.getDate("startDate"));
        // 入住截止日期
        hotelEndorsementDetail.setCheckInEndDate(nodeBusinessTrip.getDate("endDate"));
            Calendar calendar1 = Calendar.getInstance();
            calendar1.setTime(nodeBusinessTrip.getDate("startDate"));
            calendar1.add(Calendar.DATE,1);
        //离店开始日期为入住日期+1
        hotelEndorsementDetail.setCheckOutBeginDate(calendar1.getTime());
            Calendar calendar2 = Calendar.getInstance();
            calendar2.setTime(nodeBusinessTrip.getDate("endDate"));
            calendar2.add(Calendar.DATE,1);
        //离店截止日期为入住截止日期+1
        hotelEndorsementDetail.setCheckOutEndDate(calendar2.getTime());

        ArrayList<PassengerDetail> list = getPassengers(nodeBusinessTrip, personCode, tenant, openType, channel);
        // 城市
        JSONObject hotelCities = nodeBusinessTrip.getJSONObject("hotelCities");
        ArrayList<String> toCitesList = new ArrayList<>(hotelCities.keySet());

        // 预定类型 国内
        hotelEndorsementDetail.setProductType(HotelProductType.Domestic);
        hotelEndorsementDetail.setToCities(toCitesList);
        hotelEndorsementDetail.setPassengerList(list);

        ArrayList<Integer> averagePrices = new ArrayList<>();
        for (int i = 0; i < travelList.size(); i++) {
            JSONObject travel = travelList.getJSONObject(i);
            if (null != travel.getBigDecimal("yghotelcost") && travel.getBigDecimal("yghotelcost").compareTo(new BigDecimal(0)) > 0) {
                if (travel.getBigDecimal("hotelstandard") != null && travel.getBigDecimal("hotelstandard").intValue() > 0) {
                    averagePrices.add(travel.getBigDecimal("hotelstandard").intValue());
                }
            }
        }
        if (averagePrices.size() > 0) {
            Collections.sort(averagePrices);
            hotelEndorsementDetail.setAveragePrice(averagePrices.get(averagePrices.size() - 1));
        }
        hotelEndorsementDetails.add(hotelEndorsementDetail);

        JSONArray internationalCityArray =  nodeBusinessTrip.getJSONObject("special").getJSONArray("internationalCityList");
        //国际酒店
        if(!CollectionUtils.isEmpty(internationalCityArray)) {
            HotelEndorsementDetail hotelEndorsementDetail2 = new HotelEndorsementDetail();
            BeanUtils.copyProperties(hotelEndorsementDetail, hotelEndorsementDetail2);
            // 入住日期
            hotelEndorsementDetail2.setCheckInBeginDate(nodeBusinessTrip.getDate("startDate"));
            // 入住截止日期
            hotelEndorsementDetail2.setCheckInEndDate(nodeBusinessTrip.getDate("endDate"));
            ArrayList<String> strings = (ArrayList<String>) JSONObject.parseArray(internationalCityArray.toString(), String.class);
            hotelEndorsementDetail2.setToCities(strings);
            // 预定类型 国内
            hotelEndorsementDetail2.setProductType(HotelProductType.International);
            hotelEndorsementDetails.add(hotelEndorsementDetail2);
        }
        return hotelEndorsementDetails;
    }

    /**
     * 火车信息组装
     *
     * @param travelList       申请单行程明细
     * @param nodeBusinessTrip 申请单信息
     * @param personCode       员工编号
     * @param tenant           租户ID
     * @param openType         NC还是SAAS
     * @param channel
     * @return {@link TrainEndorsementDetail} 携程审批单火车票信息
     */
    private ArrayList<TrainEndorsementDetail> getTrainInfos(JSONArray travelList, JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel channel) {
        ArrayList<TrainEndorsementDetail> trainEndorsementDetails = new ArrayList<>();
        TrainEndorsementDetail trainEndorsementDetail = new TrainEndorsementDetail();
        // 出发日期
        trainEndorsementDetail.setDepartBeginDate(nodeBusinessTrip.getDate("startDate"));
        // 到达日期
        trainEndorsementDetail.setDepartEndDate(nodeBusinessTrip.getDate("endDate"));
        //出行人详情
        ArrayList<PassengerDetail> list = getPassengers(nodeBusinessTrip, personCode, tenant, openType, channel);
        trainEndorsementDetail.setPassengerList(list);
        // 预定类型 国内
        trainEndorsementDetail.setProductType(TrainProductType.Domestic);

        // 出发城市和到达城市
        ArrayList<String> fromCitesList = new ArrayList<>();
        ArrayList<String> toCitesList = new ArrayList<>();

        for (int i = 0; i < travelList.size(); i++) {
            JSONObject travel = travelList.getJSONObject(i);
            if (null != travel.getString("tripType") && "RT".equals(travel.getString("tripType"))) {
                if (null != travel.getString("tripWay") && "火车".equals(travel.getString("tripWay"))) {
                    logger.info("向携程推送数据:组织火车数据！");
                    if (null != travel.getString("fromCity") && StringUtils.isNotBlank(travel.getString("fromCity"))
                            && null != travel.getString("toCity") && StringUtils.isNotBlank(travel.getString("toCity"))) {
                        fromCitesList.add(travel.getString("fromCity").split("-")[0]);
                        toCitesList.add(travel.getString("toCity").split("-")[0]);
                    } else {
                        logger.info("向携程推送数据错误：单据明细数据主键=" + travel.getString("pk") + ",火车出发城市不能为空！");
                        continue;
                    }
                    trainEndorsementDetail.setTripType(TripTypeEnum.RoundTrip);
                }
            } else {
                if (null != travel.getString("tripWay") && "火车".equals(travel.getString("tripWay"))) {
                    logger.info("向携程推送数据:组织火车数据！");
                    if (null != travel.getString("fromCity") && StringUtils.isNotBlank(travel.getString("fromCity"))
                            && null != travel.getString("toCity") && StringUtils.isNotBlank(travel.getString("toCity"))) {
                        fromCitesList.add(travel.getString("fromCity").split("-")[0]);
                        toCitesList.add(travel.getString("toCity").split("-")[0]);
                    } else {
                        logger.info("向携程推送数据错误：单据明细数据主键=" + travel.getString("pk") + ",火车出发城市不能为空！");
                        continue;
                    }
                    if (!"2".equals(String.valueOf(trainEndorsementDetail.getTripType()))) {
                        trainEndorsementDetail.setTripType(TripTypeEnum.SingleWay);
                    }
                }
            }
        }

        trainEndorsementDetail.setFromCities(fromCitesList);
        trainEndorsementDetail.setToCities(toCitesList);
        if (fromCitesList.size() > 0 && toCitesList.size() > 0) {
            trainEndorsementDetails.add(trainEndorsementDetail);
        }
        return trainEndorsementDetails;
    }

    /**
     * 机票信息组装
     *
     * @param travelList       申请单行程明细
     * @param nodeBusinessTrip 申请单信息
     * @param personCode       员工编号
     * @param tenant           租户ID
     * @param openType         NC还是SAAS
     * @param channel
     * @return {@link FlightEndorsementDetail} 携程审批单航程信息
     */
    private ArrayList<FlightEndorsementDetail> getFlightInfos(JSONArray travelList, JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel channel) {
        ArrayList<FlightEndorsementDetail> flightEndorsementDetails = new ArrayList<>();
        logger.info("向携程推送数据:组织飞机数据！");

        FlightEndorsementDetail flightEndorsementDetail = new FlightEndorsementDetail();
        //增加国际航班对象，方便赋值
        FlightEndorsementDetail flightEndorsementDetail2 = new FlightEndorsementDetail();
        if (nodeBusinessTrip.getDate("startDate") == null) {
            logger.info("携程的出发日期为空");
        } else {
            // 出发日期
            flightEndorsementDetail.setDepartBeginDate(nodeBusinessTrip.getDate("startDate"));
            flightEndorsementDetail.setReturnBeginDate(nodeBusinessTrip.getDate("startDate"));
            flightEndorsementDetail2.setDepartBeginDate(nodeBusinessTrip.getDate("startDate"));
            flightEndorsementDetail2.setReturnBeginDate(nodeBusinessTrip.getDate("startDate"));
        }
        if (nodeBusinessTrip.getDate("endDate") == null) {
            logger.info("携程的结束日期为空");
        } else {
            // 到达日期
            flightEndorsementDetail.setDepartEndDate(nodeBusinessTrip.getDate("endDate"));
            flightEndorsementDetail.setReturnEndDate(nodeBusinessTrip.getDate("endDate"));
            flightEndorsementDetail2.setDepartEndDate(nodeBusinessTrip.getDate("endDate"));
            flightEndorsementDetail2.setReturnEndDate(nodeBusinessTrip.getDate("endDate"));
        }
        //实际出行人详情
        ArrayList<PassengerDetail> list = getPassengers(nodeBusinessTrip, personCode, tenant, openType, channel);
        flightEndorsementDetail.setPassengerList(list);
        flightEndorsementDetail2.setPassengerList(list);

        // 国内航程出发城市
        ArrayList<String> fromCitesList = new ArrayList<>();
        //国内航程到达城市
        ArrayList<String> toCitesList = new ArrayList<>();
        //国际航程出发城市
        ArrayList<String> internationalFromCityList = new ArrayList<>();
        //国际航程到达城市
        ArrayList<String> internationalToCityList = new ArrayList<>();
        //国内往返/单程，默认单程
        FlightWayType dFlightWayType = FlightWayType.SingleTrip;
        //国际往返/单程，默认单程
        FlightWayType iFlightWayType = FlightWayType.SingleTrip;

        for (int i = 0; i < travelList.size(); i++) {
            JSONObject travel = travelList.getJSONObject(i);
            //单程往返，RT往返 OW单程
            String tripType = travel.getString("tripType");
            //出行方式，飞机/火车等
            String tripWay = travel.getString("tripWay");
            //国内国际，I国际 D国内
            String airportType = travel.getString("airportType");
            //出发城市，飞机对应的格式为：城市名-机场名
            String fromCity = travel.getString("fromCity");
            //到达城市，飞机对应的格式为：城市名-机场名
            String toCity = travel.getString("toCity");
            if ("飞机".equals(tripWay)) {
                if (StringUtils.isNotEmpty(fromCity) && StringUtils.isNotEmpty(toCity)) {
                    if ("I".equals(airportType)) {
                        internationalFromCityList.add(fromCity.split("-")[0]);
                        internationalToCityList.add(toCity.split("-")[0]);
                    } else {
                        fromCitesList.add(fromCity.split("-")[0]);
                        toCitesList.add(toCity.split("-")[0]);
                    }
                } else {
                    logger.info("向携程推送数据错误：单据明细数据主键=" + travel.getString("pk") + ",飞机出发城市不能为空！");
                    continue;
                }
                //国内国际的往返类型，如果有一个行程是往返的就设置成往返
                if ("I".equals(airportType) && "RT".equals(tripType)) {
                    iFlightWayType = FlightWayType.RoundTrip;
                } else if (!"I".equals(airportType) && "RT".equals(tripType)) {
                    dFlightWayType = FlightWayType.RoundTrip;
                }
            }
        }
        //国内国际航程
        if (fromCitesList.size() > 0 && toCitesList.size() > 0) {
            flightEndorsementDetail.setFlightWay(dFlightWayType);
            flightEndorsementDetail.setProductType(ProductType.DomesticFlight);
            flightEndorsementDetail.setFromCities(fromCitesList);
            flightEndorsementDetail.setToCities(toCitesList);
            flightEndorsementDetails.add(flightEndorsementDetail);
        }
        if (internationalFromCityList.size() > 0 && internationalToCityList.size() > 0) {
            flightEndorsementDetail2.setFlightWay(iFlightWayType);
            flightEndorsementDetail2.setProductType(ProductType.InternationalFlight);
            flightEndorsementDetail2.setFromCities(internationalFromCityList);
            flightEndorsementDetail2.setToCities(internationalToCityList);
            flightEndorsementDetails.add(flightEndorsementDetail2);
        }
        return flightEndorsementDetails;
    }

    /**
     * 获取实际出行人actualPedestrian,当实际出行人字段actualPedestrian为空时取申请人为实际出行人
     * 实际出行人actualPedestrian字段: nc用户存的是personid ,saas用户存的是userID
     *
     * @param nodeBusinessTrip 申请单信息
     * @param personCode       申请人员工号
     * @param tenant           租户ID
     * @param openType         NC还是SAAS
     * @return {@link PassengerDetail} 出行人列表
     */
    private ArrayList<PassengerDetail> getPassengers(JSONObject nodeBusinessTrip, String personCode, String tenant, String openType, BriChannel briChannel) {
        ArrayList<PassengerDetail> list = new ArrayList<>();
        String passengers = nodeBusinessTrip.getString("actualPedestrian");

        if (StringUtils.isNotBlank(passengers)) {
            String[] split = passengers.split(";");
            List<String> personIds = new ArrayList<>();
            for (String str : split) {
                if (str.split(",").length > 0) {
                    personIds.add(str.split(",")[0]);
                }
            }
            List<UcUserDto> companionUser = null;
            if ("nc".equals(openType)) {
                companionUser = iUserCenterService.getCompleteUcUserByPersonIds(personIds, tenant);
            } else {
                companionUser = iUserCenterService.getCompleteUcUserDtoByUserid(personIds, tenant);
            }
            if (companionUser != null) {
                for (UcUserDto ucUserDto : companionUser) {
                    PassengerDetailV2 passengerDetail = new PassengerDetailV2();
                    passengerDetail.setName(ucUserDto.getUserName());
                    passengerDetail.setEid(ucUserDto.getPersonCode());
                    if (briChannel.getSyncRank().equals(2)){
                        passengerDetail.setRankName(ucUserDto.getPostName());
                    }
                    list.add(passengerDetail);
                }
            } else {
                logger.info("用户中心未找到实际出行人:" + personIds.toString());
                //TODO 用户中心未找到人员时同步erp用户，再次查找。
                throw new BusinessException("用户中心未找到部分实际出行人");

            }
        }
        //制单人信息
        UcUserDto sscUser = iUserCenterService.getCompleteUcUserDtoByPersonCode(personCode, tenant);

        // 旧的实际出行人为手输格式，支持格式  张三,李四
        String companion = nodeBusinessTrip.getString("companion");
        //如果手输格式人名和制单人名一致则忽略
        if (StringUtils.isNotEmpty(companion) && !companion.equals(sscUser.getUserName())) {
            companion = companion.replaceAll("，", ",").replaceAll("、", ",").replaceAll("/", ",").replaceAll("。", ",").replaceAll(" ", "").trim();
            String[] splitCompanion = companion.split(",");
            for (String oneCompanion : splitCompanion) {
                if(StringUtils.isNotBlank(oneCompanion)){
                    String[] strings = oneCompanion.split(":");
                    PassengerDetail passengerDetail = new PassengerDetail();
                    passengerDetail.setName(strings[0]);
                    list.add(passengerDetail);
                }
            }
        }
        // 如果list为空就把申请人加进去
        if (list.size() == 0 ) {
            PassengerDetailV2 passengerDetail = new PassengerDetailV2();
            passengerDetail.setEid(personCode);
            if (briChannel.getSyncRank().equals(2)) {

                passengerDetail.setRankName(sscUser.getPostName());
            }
            passengerDetail.setName(sscUser.getUserName());
            list.add(passengerDetail);
        }
        return list;
    }
    /**
     * 转换companion中的字符
     * @param companion
     * @return
     */
    public static String convertTraveler(String companion){
        String convertStr = companion;
        if (companion.contains("（")){
            convertStr = companion.replaceAll("（",",");
        }
        if (companion.contains("(")){
            convertStr = convertStr.replaceAll("\\(",",");
        }
        if (companion.contains("）")){
            convertStr = convertStr.replaceAll("）","");
        }
        if (companion.contains(")")){
            convertStr = convertStr.replaceAll("\\)","");
        }
        if (companion.contains("，")){
            convertStr = convertStr.replaceAll("，",",");
        }
        if (companion.contains("、")){
            convertStr = convertStr.replaceAll("、",",");
        }
        return convertStr;
    }

    @Override
    public void syncCtripBCUsers(List<CtripBCUser> ctripBCUsers,  CtripBCConfig config , String email, BriChannel briChannel) {
        String appKey = config.getAppKey();
        String appSecurty = config.getAppSecurity();
        String corporationId = config.getCorporationId();
        String subAccountName = config.getSubAccountName();
        String tenantId = ctripBCUsers.get(0).getTenant();
        OrderSearchTicketResponse ticketResponse = CorpTicketService.getEmployeeSyncTicket(appKey, appSecurty, "1.0");
        if (ticketResponse != null && ticketResponse.getStatus() != null && ticketResponse.getStatus().getSuccess()) {
            logger.info("get ticket success! ticket:" + ticketResponse.getTicket());
            AuthenticationListRequst authenticationListRequst = new AuthenticationListRequst();
            authenticationListRequst.setTicket(ticketResponse.getTicket());
            authenticationListRequst.setCorporationID(corporationId);
            authenticationListRequst.setAppkey(appKey);

            List<List<CtripBCUser>> lists = ListUtils.partition(ctripBCUsers, 500);
            for (List<CtripBCUser> ctripUserBatch : lists) {
                //特殊人员userIdList
                List<String> specialUserIdList = this.getSpecialUserIdList(ctripUserBatch, tenantId);
                List<AuthenticationInfoList> authenticationInfoLists = new ArrayList<>();
                for (CtripBCUser ctripBCUser : ctripUserBatch) {
                    //特殊人员不进行同步
                    if (specialUserIdList.contains(ctripBCUser.getUserId())) {
                        continue;
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("subAccountName" , subAccountName);
                    Authentication authencationEntity = getAuthentication(ctripBCUser,jsonObject , email, briChannel);
                    AuthenticationInfoList authenticationInfoList = new AuthenticationInfoList();
                    authenticationInfoList.setAuthentication(authencationEntity);
                    authenticationInfoList.setSequence("0");
                    authenticationInfoLists.add(authenticationInfoList);
                }
                authenticationListRequst.setAuthenticationInfoList(authenticationInfoLists);
                multipleUsersSync(authenticationListRequst);
            }
        } else {
            String errorms = String.format("get ticket failed! error message:%s", JSON.toJSONString(ticketResponse));
            logger.info("get ticket failed! error message:{}", JSON.toJSONString(ticketResponse));
            throw new RuntimeException(errorms);
        }

    }


}
